package com.taurus.myboard.controller;

import com.taurus.myboard.common.vo.Result;
import com.taurus.myboard.pojo.FileInfoVo;
import com.taurus.myboard.service.IFateDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author kanten
 * @since 2023-06-20
 */
@RestController
@RequestMapping("/myboard/data")
@Slf4j
public class DataManageController {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private IFateDataService fateDataService;

    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestParam("filename") MultipartFile file, @RequestParam("table_name") String table_name,
                             @RequestParam("head") String head, @RequestParam("partition") String partition,
                             @RequestParam("namespace") String namespace,
                             @RequestParam("drop") String drop) throws IOException {

        log.info("接收到的文件数据为：" + file);

        if (file.isEmpty()) {

            return Result.fail("上传文件为空");
        }
//        // 获取文件全名a.py
//        String fileName = file.getOriginalFilename();

        Map<String, String> data = fateDataService.upLoadData(file, table_name, Integer.parseInt(head),
                Integer.parseInt(partition), namespace, 1, drop.equalsIgnoreCase("true") ? 1 : 0);
        return Result.success("上传数据成功");
    }

    @PostMapping("/uploadInfo")
    public Result uploadInfo(@RequestBody FileInfoVo fileInfoVo) throws IOException {

        Map<String, String> data = fateDataService.saveFileInfo(fileInfoVo);
        return Result.success("上传数据成功");
    }

    @GetMapping("/download")
    public Result downloadData(){
        //TBD
        return Result.success();
    }

    @GetMapping("/queryUploadHistory")
    public Result<Map<String, Object>> queryUploadHistory(@RequestParam(value = "jobId", required = false) String jobId,
                                @RequestParam(value = "limit", required = false) Integer limit,
                                @RequestParam(value = "pageNo") Long pageNo,
                                @RequestParam(value = "pageSize") Long pageSize){
        if (!StringUtils.hasLength(jobId))jobId="";
        if (limit == null) {
            limit = -1;
        }
        // 分页
        Long headIndex = (pageNo - 1) * pageSize + 1;
        Long tailIndex = pageNo * pageSize;

        Map<String, Object> data = fateDataService.queryUploadHistory(jobId, limit, headIndex, tailIndex);
        return Result.success(data);
    }

}
